package ve.usb.ddp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import ve.usb.cohesion.runtime.CohesionAction;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import ve.usb.cohesion.runtime.HibernateUtil;
import ve.usb.ddp.hibernate.*;

import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.hibernate.LockMode;

/**
 * 
 */
public class AccionesCU002IniciarSesion extends CohesionAction {
    
/**
     * Called by Struts for the execution of action A_Conectarse.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Conectarse(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"A_Pre_ManejoGeneral", "A_Pre_Inicio", "A_Pre_Inicio", };
        final int SALIDA_0 = 0;
        final int SALIDA_1 = 1;
        final int SALIDA_2 = 2;

        int salida = SALIDA_0;
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            F_Conectarse fF_Conectarse = (F_Conectarse)form;
            /*Empieza nuestro codigo*/
            List<Usuario> usuarios = s.createQuery("from Usuario user where user.user_login=:login")
                    .setString("login", fF_Conectarse.getLogin()).list();
            if (!usuarios.isEmpty()){
                String encryptedPass = usuarios.get(0).encryptPass(fF_Conectarse.getPassword());

                if(usuarios.size() == 1 && usuarios.get(0).getPassword().equals(encryptedPass)
                        && fF_Conectarse.getLogin().length() > 0 && fF_Conectarse.getPassword().length() > 0){
                    HttpSession httpSess = request.getSession();
                    Usuario user = usuarios.get(0);
                    Hibernate.initialize("user");
                    httpSess.setAttribute("u_conectado", user);
                    fF_Conectarse.setPassword("");
                    fF_Conectarse.setLogin("");
                    short tipo = user.getTipo();
                    switch (tipo){
                        //Director DDP
                        case 2:
                            new CohesionActor(CohesionActor.ACTOR_director_DDP)
                            .setMe(request);
                            break;
                        //Encargado PAA
                        case 4:
                            new CohesionActor(CohesionActor.ACTOR_encargado_paa)
                            .setMe(request);
                            break;
                        //Encargado PAI
                        case 8:
                            new CohesionActor(CohesionActor.ACTOR_encargado_pai)
                            .setMe(request);
                            break;
                        //Encargado PAS
                        case 16:
                            new CohesionActor(CohesionActor.ACTOR_encargado_pas)
                            .setMe(request);
                            break;
                        //Encargodo PRD
                        case 32:
                            new CohesionActor(CohesionActor.ACTOR_encargado_prd)
                            .setMe(request);
                            break;
                    }
                }else{
                    salida = SALIDA_2;
                }

                if(usuarios.size() != 1) {
                    salida = SALIDA_1;
                }
            }else{
                salida = SALIDA_1;
            }
            /*Termina nuestro codigo*/
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try { s.close(); } catch (Exception ex2) {}
        }
        if (salida==1) {
          request.setAttribute("msg",
            getResources(request).getMessage("A_Conectarse.msg1"));
        }
        if (salida==2) {
          request.setAttribute("msg",
            getResources(request).getMessage("A_Conectarse.msg2"));
        }

        return mapping.findForward(SALIDAS[salida]);
    }

/**
     * Called by Struts for the execution of action A_Pre_Inicio.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Pre_Inicio(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"V_InicioSesion", };
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try { s.close(); } catch (Exception ex2) {}
        }
        return mapping.findForward(SALIDAS[salida]);
    }

/**
     * Called by Struts for the execution of action A_Pre_OlvidoPass.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_Pre_OlvidoPass(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"V_OlvidoPass", };
        final int SALIDA_0 = 0;

        int salida = SALIDA_0;
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try { s.close(); } catch (Exception ex2) {}
        }
        return mapping.findForward(SALIDAS[salida]);
    }

/**
     * Called by Struts for the execution of action A_OlvidoPass.
     * 
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward A_OlvidoPass(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Salidas
        final String[] SALIDAS = {"A_Pre_Inicio", "A_Pre_OlvidoPass", "V_OlvidoPass", };
        final int SALIDA_0 = 0;
        final int SALIDA_1 = 1;
        final int SALIDA_2 = 2;

        int salida = SALIDA_0;
        Session s = HibernateUtil.getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            F_OlvidoPass fF_OlvidoPass = (F_OlvidoPass)form;
            /* Empieza codigo propio */
            String userLogin = fF_OlvidoPass.getLogin();
            String correo = fF_OlvidoPass.getCorreo();
            List<Usuario> users = s.createQuery("from Usuario user where user.user_login=:login")
                    .setString("login", userLogin).list();
            if(users.size() == 1){
                
                // Generar nuevo password
                String newPass = Usuario.getRandomPass();
                // Aplicar SHA-1 al nuevo password
                String newPassEncrypted = users.get(0).encryptPass(newPass);

                // TODO Hacer el correo con nuevo password
                String TITULO = "DDP Online: Prueba de envio de correo";
                String MENSAJE = "Hola " + users.get(0).getNombreCompleto() + ".\n";
                MENSAJE += "Tu nuevo password es " + newPass;

                // Enviar el nuevo password al correo
                final String CORREO_REMITENTE = "notificacion.ddp@gmail.com";
                final String PASS_CORREO_REMITENTE = "ddponline";
                // Propiedades de la conexión
                Properties props = new Properties();
                props.setProperty("mail.smtp.host", "smtp.gmail.com");
                props.setProperty("mail.smtp.starttls.enable", "true");
                // Puerto de gmail para envio de correos
                props.setProperty("mail.smtp.port", "587");
                // Nombre del usuario
                props.setProperty("mail.smtp.user", CORREO_REMITENTE);
                // Definimos si se requiere o no usuario y password para conectarse
                props.setProperty("mail.smtp.auth", "true");
                // Preparamos la sesion
                javax.mail.Session session = javax.mail.Session.getDefaultInstance(props);
                // Construimos el mensaje
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(CORREO_REMITENTE));
                // Agregamos DESTINATARIO
                message.addRecipients(Message.RecipientType.TO, correo);
                // Seteamos ASUNTO
                message.setSubject(TITULO);
                // Agregamos MENSAJE DE TEXTO O HTML
                message.setText(MENSAJE);
                // Especificamos el protocolo a usar, en nuestro caso smtp
                Transport t = session.getTransport("smtp");
                t.connect(CORREO_REMITENTE, PASS_CORREO_REMITENTE);
                //Transport.send(message);
                // Se envia el mensaje a todos lo destinatarios en el array Recipients
                t.sendMessage(message, message.getAllRecipients());
                // Cierre.
                t.close();

                // Update del nuevo password cifrado en base de datos
                users.get(0).setPassword(newPassEncrypted);
                s.update(users.get(0));
                s.flush();


                fF_OlvidoPass.setCorreo("");
                fF_OlvidoPass.setLogin("");
            }else{
                salida = SALIDA_1;
            }
            /* Termina codigo propio */
            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        } finally {
            try { s.close(); } catch (Exception ex2) {}
        }
        if (salida==0) {
          request.setAttribute("msg",
            getResources(request).getMessage("A_OlvidoPass.msg0"));
        }
        if (salida==1) {
          request.setAttribute("msg",
            getResources(request).getMessage("A_OlvidoPass.msg1"));
        }
        if (salida==2) {
          request.setAttribute("msg",
            getResources(request).getMessage("A_OlvidoPass.msg2"));
        }

        return mapping.findForward(SALIDAS[salida]);
    }



}